//
//  WantedBondTableViewController.m
//  bondwatch_purecode
//
//  Created by Jason Yuan on 6/15/15.
//  Copyright (c) 2015 Sumridge. All rights reserved.
//

#import "WantedBondTableViewController.h"
#import "SearchViewController.h"

@interface WantedBondTableViewController () <SearchViewControllerDelegate>
{
    NSMutableArray *wantedArray;
}

@end

@implementation WantedBondTableViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
//    self.title = @"Wanted";
    
    UIBarButtonItem *settingBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Settings"] style:UIBarButtonItemStylePlain target:self action:@selector(settingBarButtonPressed:)];
    settingBarButton.tintColor = SUMRIDGECOLOR;
    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Back"] style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonPressed:)];
    backBarButton.tintColor = SUMRIDGECOLOR;
    UIBarButtonItem *saveBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveBarButtonPressed:)];
    saveBarButton.tintColor = [UIColor blackColor];
    NSArray *leftItems = @[settingBarButton, backBarButton, saveBarButton];
    self.navigationItem.leftBarButtonItems = leftItems;
    
    UIBarButtonItem *searchBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Search"] style:UIBarButtonItemStylePlain target:self action:@selector(searchBarButtonPressed:)];
    searchBarButton.tintColor = SUMRIDGECOLOR;
    NSArray *rightItems = @[searchBarButton];
    self.navigationItem.rightBarButtonItems = rightItems;
    
    self.tableView.separatorInset = UIEdgeInsetsZero;
    self.tableView.layoutMargins = UIEdgeInsetsZero;
    
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [self.tableView setTableFooterView:view];
}

- (void)settingBarButtonPressed:(id)sender {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (void)backBarButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)saveBarButtonPressed:(id)sender {
    NSString *params = [[NSString alloc] init];
    for (int i = 0; i < [wantedArray count]; i++) {
        NSDictionary *dictionary = [wantedArray objectAtIndex:i];
        NSString *cusip = [dictionary objectForKey:@"cusip"];
        params = [params stringByAppendingString:[NSString stringWithFormat:@"%@,", cusip]];
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?prwId=%@", ADDWATCHBONDURL, [Shared shared].prwId]]];
    [request setHTTPMethod:@"POST"];
    
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSMutableData *postBody = [NSMutableData data];
    [postBody appendData:[params dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postBody];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    operation.responseSerializer = [AFHTTPResponseSerializer serializer];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        DDLogVerbose(@"Save wanted bond result:\n%@", result);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DDLogError(@"Save wanted bond error:\n%@", error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [[NSOperationQueue mainQueue] addOperation:operation];
}

- (void)searchBarButtonPressed:(id)sender {
    SearchViewController *searchViewController = [[SearchViewController alloc] init];
    searchViewController.delegate = self;
    [self.navigationController pushViewController:searchViewController animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (wantedArray != nil) {
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        return [wantedArray count];
    } else {
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WantedBondCell"];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"WantedBondCell"];
        cell.separatorInset = UIEdgeInsetsZero;
        cell.layoutMargins = UIEdgeInsetsZero;
    }
    
    NSDictionary *data = [wantedArray objectAtIndex:indexPath.row];
    cell.textLabel.textColor = SUMRIDGECOLOR;
    cell.textLabel.text = [data objectForKey:@"description"];
    
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [wantedArray removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 36.0;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

#pragma mark - Search view delegate

- (void)selectWatchBond:(NSDictionary *)data {
    if (data) {
        if (wantedArray == nil) {
            wantedArray = [[NSMutableArray alloc] init];
        }
        
        [wantedArray addObject:data];
        [self.tableView reloadData];
    }
}

#pragma mark - SavedList view delegate

- (void)addListData:(NSString *)listId {
    
}

@end
